package com.hzw.monitor.mysqlbinlog.connection;

/**
 * 
 * @author zhiqiang.liu
 * @2016年1月1日
 *
 */
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.hzw.monitor.mysqlbinlog.netty.server.MyNioSocketChannel;
import com.hzw.monitor.mysqlbinlog.utils.LoggerUtils;

public class ConnectionFactory {
	private static final Logger logger = LogManager.getLogger(ConnectionFactory.class);
	private static ConcurrentHashMap<String, MyNioSocketChannel> SocketChannelHashMap = new ConcurrentHashMap<String, MyNioSocketChannel>();

	public static void put(String key, MyNioSocketChannel value) {
		SocketChannelHashMap.put(key, value);
	}

	public static MyNioSocketChannel get(String key) {
		return SocketChannelHashMap.get(key);
	}

	public static MyNioSocketChannel remove(String key) {
		return SocketChannelHashMap.remove(key);
	}

	public static Connection makeObject(String ip, int port, String data, String runningPath, String binlogPositionPath,
			String initialFilename, long initialPosition) {
		Connection myConn = null;

		if (null != ip && port >= 0) {
			try {
				// 在这里创建具体的对象
				SocketAddress sAddress = new InetSocketAddress(ip, port);
				SocketChannel sChannel = SocketChannel.open(sAddress);
				sChannel.configureBlocking(false);// 非阻塞
				myConn = new Connection(sChannel,
						ConnectionAttributes.parse(data).setIpPort(ip, port).setRunningZKPath(runningPath)
								.setBinlogPositionZKPath(binlogPositionPath)
								.setClientId(Long.parseLong(ip.replaceAll(".", "") + port))
								.updateBinlogNameAndPosition(initialFilename, initialPosition));
			} catch (Exception e) {
				LoggerUtils.error(logger, e.toString());
			}
		}

		// 无论如何，都返回连接，失敗則返回null
		return myConn;
	}

}
